<template>
  <div class="upload-file-modal">
    <i class="close ri-close-fill" @click="closeModal" v-if="false"></i>
    <div class="upload-file-title">
      <p>图片上传</p>
    </div>
    <div class="upload-file-content">
      <el-upload
        :action="UPLOAD_SERVER"
        accept="image/*"
        :multiple="false"
        :show-file-list="false"
        :before-upload="beforeFileUpload"
        :on-success="handleUploadResult"
        :on-error="handleUploadResult"
      >
        <div class="upload-block" v-if="!imageFile">
          <p class="upload-drag-icon">
            <img src="@/assets/images/new-drag-and-drop-file.png" alt="">
          </p>
          <p class="upload-text">将文件拖到此处或者<span>点击上传</span></p>
        </div>
        <div class="image-preview" v-if="imageFile">
          <img :src="imageFile" alt="">
        </div>
      </el-upload>
      <div class="upload-tip">支持格式：Png、Jpg、Jpeg、Svg</div>
    </div>
    <footer v-show="imageFile">
      <el-button @click="closeModal">取消</el-button>
      <el-button @click="setUploadImage" type="primary" :disabled="!imageFile">确定</el-button>
    </footer>
  </div>
</template>

<script setup>
import { ref, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { UPLOAD_SERVER } from '@/config/common.config'
import { loadImageAsync } from '../export/parse'

const emits = defineEmits(['set-image', 'close'])
const imageFile = ref(null)
const width = ref(0)
const height = ref(0)

function beforeFileUpload (file) {
  const imageExtensionsRegex = /(\.jpg|\.jpeg|\.png|\.svg)$/i
  const isPic = imageExtensionsRegex.test(file.name)
  if (!isPic) {
    ElMessage.error('只能上传图片')
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('上传的图片大小不能超过5M')
  }
  return isPic && isLt5M
}

async function handleUploadResult (response) {
  if (response.code === '0') {
    const url = response.data
    imageFile.value = url
    const data = await loadImageAsync(imageFile.value)
    width.value = data.width
    height.value = data.height
  } else {
    ElMessage.error(response.message)
  }
}

function setUploadImage () {
  if (!imageFile.value) return
  const max = Math.max(width.value, height.value)
  const ratio = max / 180
  emits('set-image', {
    url: imageFile.value,
    width: width.value > 180 ? (width.value / ratio > 180 ? 180 : width.value / ratio) : width.value,
    height: height.value > 180 ? (height.value / ratio > 180 ? 180 : height.value / ratio) : height.value
  })
}

function closeModal () {
  emits('close')
}
</script>
